package com.wizkey.dao.impl;

import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.wizkey.dao.IAssetDao;
import com.wizkey.dao.ICommentDao;
import com.wizkey.dao.IUserDao;
import com.wizkey.pojo.Asset;
import com.wizkey.pojo.Comment;
import com.wizkey.pojo.User;

/**
 * 评论接口实现类
 * <p>
 * ClassName: CommentDaoImpl
 * </p>
 */
@Repository
public class CommentDaoImpl extends BaseDaoImpl<Comment> implements ICommentDao {

	@Override
	protected Class<Comment> getEntityClass() {
		return Comment.class;
	}

	@Autowired
	private IUserDao userDao;
	@Autowired
	private IAssetDao assetDao;

	@Override
	public boolean addComment(Comment comment, String userId, String assetId) {
		comment.setCommentTime( new Timestamp(System.currentTimeMillis()));
		comment.setUserID(userId);
		comment.setAssetID(assetId);
		try {
			save(comment);
			// User user = userDao.findById(userId);
			// user.getCommentsId().add(comment.getId());
			// userDao.update(user);
			User user = userDao.findById(userId);
			user.getComments().add(comment);
			userDao.update(user);
			// commentNum
			Asset asset = assetDao.findById(assetId);
			asset.getCommentIds().add(comment.getId());
			asset.setCommentNum(asset.getCommentIds().size());
			assetDao.update(asset);
		} catch (Exception e) {
			e.printStackTrace();

			return false;
		}
		return true;
	}
	@Override
	public boolean addScore(Comment comment, String userId, String assetId) {
		
		Asset asset = assetDao.findById(assetId);
		int scoreNum = asset.getScoreNum();
		scoreNum++;
		asset.setScoreNum(scoreNum);
		asset.setScore((asset.getScore() * (scoreNum - 1) + comment.getScore()) / scoreNum);
		assetDao.update(asset);
		return false;
	}
}
